package com.gopay.bis.manager.bank.ebank;

import java.util.Map;

import javax.annotation.Resource;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.common.util.TransUtil;
import com.gopay.bis.dao.payconfig.BisBankExtConfigDAO;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.kuaiqian.ebank.KuaiQianMessage;
import com.gopay.common.domain.bank.kuaiqian.ebank.KuaiQianQueryMessage;
import com.gopay.common.domain.bank.kuaiqian.ebank.KuaiQianQueryResultMessage;
import com.gopay.common.domain.bank.kuaiqian.ebank.KuaiQianResultMessage;
import com.gopay.common.domain.bis.BaseBisBankExtConfig;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.bank.BankManagerRemoteService;
import com.gopay.remote.bank.businesses.BankService;

public class KuaiQianManager implements BankManagerRemoteService {

	@Resource(name = "kuaiQianBankServiceClient")
	private BankService kuaiQianBankServiceClient;

	@Resource(name = "kuaiQianConfig")
	private Map<String, String> kuaiQianConfig;

	@Resource(name = "bisBankExtConfigDAO")
	private BisBankExtConfigDAO bisBankExtConfigDAO;

	@Override
	public Object sign(BaseMessage baseMessage) throws GopayException {
		// 获取银行接口通道配置信息
		BaseBisBankExtConfig bankConfig = bisBankExtConfigDAO.findExtConfigByBankCodeAndBankBusProd(baseMessage.getBankBusProd(), baseMessage.getBank());
		baseMessage.setBankOrderId("KQ" + TransUtil.processOrderIdTo14Digit(baseMessage.getOrderId()));
		//设置新生接口银行码
		baseMessage.setSpecial2(bankConfig.getIntrfaceBankCode());
		KuaiQianMessage kuaiQianMessage =  (KuaiQianMessage)baseMessage;
		// 协议参数
		kuaiQianMessage.setBankUrl(kuaiQianConfig.get("KUAIQIAN.B2C.BANKURL"));
		kuaiQianMessage.setInputCharset(kuaiQianConfig
				.get("KUAIQIAN.B2C.CHARSET"));
		kuaiQianMessage.setPageUrl(kuaiQianConfig.get("KUAIQIAN.B2C.PAGEURL"));
		kuaiQianMessage.setBgUrl(kuaiQianConfig.get("KUAIQIAN.B2C.BGURL"));
		kuaiQianMessage.setVersion(kuaiQianConfig.get("KUAIQIAN.B2C.VERSION"));
		kuaiQianMessage
				.setLanguage(kuaiQianConfig.get("KUAIQIAN.B2C.LANGUAGE"));
		kuaiQianMessage
				.setSignType(kuaiQianConfig.get("KUAIQIAN.B2C.SIGNTYPE"));
		kuaiQianMessage.setPid(kuaiQianConfig.get("KUAIQIAN.B2C.PID"));
		// 买卖双方信息参数
		// 人民币账号
		kuaiQianMessage.setMerchantAcctId(kuaiQianConfig
				.get("KUAIQIAN.B2C.MERCHANTACCT"));
		kuaiQianMessage.setBankId(kuaiQianMessage.getSpecial2());

		kuaiQianMessage.setOrderAmount(baseMessage.getAmount()
				.movePointRight(2).toString());

		kuaiQianMessage.setOrderTime(baseMessage.getOrderDate());
		kuaiQianMessage.setOrderTimestamp(baseMessage.getOrderDate());
		// 支付方式
		kuaiQianMessage.setPayType(kuaiQianConfig.get("KUAIQIAN.B2C.PAYTYPE"));

		String plainStr = buildPlainStr(kuaiQianMessage);

		kuaiQianMessage.setPlainMessage(plainStr);
		BankLogUtils.printB2CManagerSignSendLog(kuaiQianMessage);
		String signMsg = (String) kuaiQianBankServiceClient
				.sign(kuaiQianMessage);
		kuaiQianMessage.setSignMessage(signMsg);
		BankLogUtils.printB2CManagerSignReturnLog(kuaiQianMessage);
		kuaiQianMessage.setSignMsg(signMsg);
		return kuaiQianMessage;
	}

	@Override
	public Object verify(BaseMessage message) throws GopayException {
		KuaiQianResultMessage resultMsg = (KuaiQianResultMessage) message;
		String verifyStr = buildVerifyStr(resultMsg);
		resultMsg.setPlainMessage(verifyStr);
		BankLogUtils.printB2CManagerVerifySendLog(resultMsg);
		Boolean isVerify = (Boolean) kuaiQianBankServiceClient
				.verify(resultMsg);
		BankLogUtils.printB2CManagerVerifyReturnLog(message, isVerify);
		return isVerify.booleanValue();

	}

	@Override
	public Object query(Object message) throws GopayException {
		KuaiQianQueryMessage queryMessage = (KuaiQianQueryMessage) message;

		// 字符集 固定值：1 1代表UTF-8
		queryMessage
				.setInputCharset(kuaiQianConfig.get("KUAIQIAN.B2C.CHARSET"));
		// 查询接口版本 固定值：v2.0注意为小写字母
		queryMessage.setVersion(kuaiQianConfig.get("KUAIQIAN.B2C.VERSION"));
		// 签名类型 固定值：1 1代表MD5加密签名方式
		queryMessage.setSignType(kuaiQianConfig
				.get("KUAIQIAN.B2C.QUERYSIGNTYPE"));
		// 人民币账号
		// 本参数用来指定接收款项的快钱用户的人民币账号
		queryMessage.setMerchantAcctId(kuaiQianConfig
				.get("KUAIQIAN.B2C.MERCHANTACCT"));
		// 查询方式 固定选择值：0、1
		// 0按商户订单号单笔查询（返回该订单信息）
		// 1按交易结束时间批量查询（只返回成功订单）
		queryMessage.setQueryType(kuaiQianConfig.get("KUAIQIAN.B2C.QUERYTYPE"));
		// 查询模式 固定值：1 1代表简单查询（返回基本订单信息）
		queryMessage.setQueryMode(kuaiQianConfig.get("KUAIQIAN.B2C.QUERYMODE"));
		// 交易开始时间 数字串，一共14位
		// 格式为：年[4位]月[2位]日[2位]时[2位]分[2位]秒[2位]，例如：20071117020101
		if (queryMessage.getStartTime() == null) {
			queryMessage.setStartTime("");
		}
		// 交易结束时间 数字串，一共14位
		// 格式为：年[4位]月[2位]日[2位]时[2位]分[2位]秒[2位]，例如：20071117020101
		if (queryMessage.getEndTime() == null) {
			queryMessage.setEndTime("");
		}
		// 请求记录集页码 在查询结果数据总量很大时，快钱会将支付结果分多次返回。本参数表示商户需要得到的记录集页码。
		// 默认为1，表示第1页。
		if (queryMessage.getRequestPage() == null) {
			queryMessage.setRequestPage("");
		}

		String plainStr = buildQueryPlainStr(queryMessage);
		queryMessage.setPlainStr(plainStr);
		BankLogUtils.printB2CManagerQuerySendLog(queryMessage, queryMessage.getPlainStr());
		KuaiQianQueryResultMessage result = (KuaiQianQueryResultMessage) kuaiQianBankServiceClient
				.query(queryMessage);
		result.setOutStlmCd(BankConstants.BANK_LOGO_KUAIQIAN);
		BankLogUtils.printB2CManagerQueryReturnLog(result);
		return result;
	}

	public String buildPlainStr(KuaiQianMessage kuaiQianMessage) {

		String signMsgVal = "";
		signMsgVal = appendParam(signMsgVal, "inputCharset",
				kuaiQianMessage.getInputCharset());
		signMsgVal = appendParam(signMsgVal, "pageUrl",
				kuaiQianMessage.getPageUrl());
		signMsgVal = appendParam(signMsgVal, "bgUrl",
				kuaiQianMessage.getBgUrl());
		signMsgVal = appendParam(signMsgVal, "version",
				kuaiQianMessage.getVersion());
		signMsgVal = appendParam(signMsgVal, "language",
				kuaiQianMessage.getLanguage());
		signMsgVal = appendParam(signMsgVal, "signType",
				kuaiQianMessage.getSignType());
		signMsgVal = appendParam(signMsgVal, "merchantAcctId",
				kuaiQianMessage.getMerchantAcctId());
		signMsgVal = appendParam(signMsgVal, "payerName",
				kuaiQianMessage.getPayerName());
		signMsgVal = appendParam(signMsgVal, "payerContactType",
				kuaiQianMessage.getPayerContactType());
		signMsgVal = appendParam(signMsgVal, "payerContact",
				kuaiQianMessage.getPayerContact());
		signMsgVal = appendParam(signMsgVal, "orderId",
				kuaiQianMessage.getBankOrderId());
		signMsgVal = appendParam(signMsgVal, "orderAmount",
				kuaiQianMessage.getOrderAmount());
		signMsgVal = appendParam(signMsgVal, "orderTime",
				kuaiQianMessage.getOrderTime());
		signMsgVal = appendParam(signMsgVal, "productName",
				kuaiQianMessage.getProductName());
		signMsgVal = appendParam(signMsgVal, "productNum",
				kuaiQianMessage.getProductNum());
		signMsgVal = appendParam(signMsgVal, "productId",
				kuaiQianMessage.getProductId());
		signMsgVal = appendParam(signMsgVal, "productDesc",
				kuaiQianMessage.getProductDesc());
		signMsgVal = appendParam(signMsgVal, "ext1", kuaiQianMessage.getExt1());
		signMsgVal = appendParam(signMsgVal, "ext2", kuaiQianMessage.getExt2());
		signMsgVal = appendParam(signMsgVal, "payType",
				kuaiQianMessage.getPayType());
		signMsgVal = appendParam(signMsgVal, "bankId",
				kuaiQianMessage.getBankId());
		signMsgVal = appendParam(signMsgVal, "redoFlag",
				kuaiQianMessage.getRedoFlag());
		signMsgVal = appendParam(signMsgVal, "pid", kuaiQianMessage.getPid());
		return signMsgVal;
	}

	public String buildVerifyStr(KuaiQianResultMessage message) {
		String merchantSignMsgVal = "";
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "merchantAcctId",
				message.getMerchantAcctId());
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "version",
				message.getVersion());
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "language",
				message.getLanguage());
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "signType",
				message.getSignType());
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "payType",
				message.getPayType());
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "bankId",
				message.getBankId());
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "orderId",
				message.getBankOrderId());
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "orderTime",
				message.getOrderTime());
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "orderAmount",
				message.getOrderAmount());
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "dealId",
				message.getDealId());
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "bankDealId",
				message.getBankDealId());
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "dealTime",
				message.getDealTime());
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "payAmount",
				message.getPayAmount());
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "fee",
				message.getFee());
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "ext1",
				message.getExt1());
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "ext2",
				message.getExt2());
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "payResult",
				message.getPayResult());
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "errCode",
				message.getErrCode());
		return merchantSignMsgVal;
	}

	public String buildQueryPlainStr(KuaiQianQueryMessage queryMessage) {
		String signMsgParam = "";
		signMsgParam = appendParam(signMsgParam, "inputCharset",
				queryMessage.getInputCharset());
		signMsgParam = appendParam(signMsgParam, "version",
				queryMessage.getVersion());
		signMsgParam = appendParam(signMsgParam, "signType",
				queryMessage.getSignType());
		signMsgParam = appendParam(signMsgParam, "merchantAcctId",
				queryMessage.getMerchantAcctId());
		signMsgParam = appendParam(signMsgParam, "queryType",
				queryMessage.getQueryType());
		signMsgParam = appendParam(signMsgParam, "queryMode",
				queryMessage.getQueryMode());
		signMsgParam = appendParam(signMsgParam, "startTime",
				queryMessage.getStartTime());
		signMsgParam = appendParam(signMsgParam, "endTime",
				queryMessage.getEndTime());
		signMsgParam = appendParam(signMsgParam, "requestPage",
				queryMessage.getRequestPage());
		signMsgParam = appendParam(signMsgParam, "orderId",
				queryMessage.getBankOrderId());
		signMsgParam = appendParam(signMsgParam, "key",
				kuaiQianConfig.get("KUAIQIAN.QUERY.B2C.KEY"));
		return signMsgParam;
	}

	public String appendParam(String returns, String paramId, String paramValue) {
		if (returns != null && !"".equals(returns)) {
			if (paramValue != null && !"".equals(paramValue)) {

				returns += "&" + paramId + "=" + paramValue;
			}

		} else {

			if (paramValue != null && !"".equals(paramValue)) {
				returns = paramId + "=" + paramValue;
			}
		}

		return returns;
	}

	@Override
	public Object dayend(BaseMessage base) throws GopayException, Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object refund(BaseMessage base) throws GopayException {
		// TODO Auto-generated method stub
		return null;
	}

}
